package com.xm.queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 阻塞队列
 *   特点：固定容量，基于数组实现。
 *   实现：单锁，有界队列
 *   原因：数组操作轻量，单锁开销可接受
 */
public class TestArrayBlockingQueue06 {
    public static void main(String[] args) {
        BlockingQueue<Integer> arrayBlockingQueue = new ArrayBlockingQueue<Integer>(3);

        //非阻塞添加（返回 true/false）
        boolean success = arrayBlockingQueue.offer(1);
        System.out.println(success);
        //阻塞添加
        try {
            arrayBlockingQueue.put(2);
            arrayBlockingQueue.put(3);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(arrayBlockingQueue);

        //超时添加
        try {
            boolean timedSuccess = arrayBlockingQueue.offer(4, 1, TimeUnit.SECONDS);
            System.out.println(timedSuccess);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println(arrayBlockingQueue);
    }
}
